<template>
    <div style="background-color: #F2F2F2; padding: 20px;">
        <el-row>
            <el-col :span="4">
                <div class="grid-content title-wrapper" style="margin-bottom: 20px;">
                    <el-breadcrumb separator-class="el-icon-arrow-right">
                        <el-breadcrumb-item style="font-size: 18px;">配送监控</el-breadcrumb-item>
                    </el-breadcrumb>
                </div>
            </el-col>
        </el-row>
        <el-row>
            
        </el-row>

        <el-row style="margin-top: 10px;">

            <el-col :span="3">
                <el-input
                    placeholder="订单编号"
                    v-model="param.orderId"
                    clearable>
                </el-input>
            </el-col>

            <el-col :span="3" :offset="1">
              <template>
                <el-select v-model="param.status" clearable placeholder="配送状态">
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                    <span :style="{ color: item.color }">{{ item.label }}</span>
                  </el-option>
                </el-select>
              </template>
            </el-col>

            

            <el-col :span="3" :offset="1">
                <template>
                    <el-select v-model="param.cityId" clearable placeholder="所在城市">
                        <el-option
                        v-for="item in cityOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </template>
            </el-col>

            <el-col :span="3" :offset="1">
                <template>
                    <el-select v-model="param.districtId" clearable placeholder="所在区域">
                        <el-option
                        v-for="item in districtOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </template>
            </el-col>

            <el-col :span="6" :offset="1">
                <el-date-picker
                    v-model="param.paymentTime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="下单时间"
                    end-placeholder="下单时间"
                ></el-date-picker>
            </el-col>

        </el-row>

        <el-row style="margin-top: 20px;">

            <el-col :span="3">
                <el-input
                    type="number" 
                    :min="0"  
                    :max="999" 
                    placeholder="配送时长"
                    v-model="param.minDeliveryTime"
                    clearable>
                </el-input>
            </el-col>

            <el-col :span="1" style="display: flex; justify-content: center; align-items: center;">
                <span style="padding-top: 8px;">～</span>
            </el-col>
            
            <el-col :span="3">
                <el-input
                    type="number" 
                    :min="0"  
                    :max="999" 
                    placeholder="配送时长"
                    v-model="param.maxDeliveryTime"
                    clearable>
                </el-input>
            </el-col>

            <el-col :span="3" :offset="1">
                <el-input
                    type="number" 
                    :min="0"  
                    :max="999" 
                    placeholder="商品数量"
                    v-model="param.minQuantity"
                    clearable>
                </el-input>
            </el-col>

            <el-col :span="1" style="display: flex; justify-content: center; align-items: center;">
                <span style="padding-top: 8px;">～</span>
            </el-col>
            
            <el-col :span="3">
                <el-input
                    type="number" 
                    :min="0"  
                    :max="999" 
                    placeholder="商品数量"
                    v-model="param.maxQuantity"
                    clearable>
                </el-input>
            </el-col>

            <el-col :span="2" :offset="1">
                <el-button type="primary" plain @click="queryDeliveryByConditionBtn">查询</el-button>
            </el-col>

            <el-col :span="2">
                <el-button type="info" plain @click="resetForm">重置</el-button>
            </el-col>
        </el-row>


        <el-table 
            :data="deliveryList" 
            style="width: 100%; margin-top: 20px;" 
            border
            stripe
            row-key="id">
            <el-table-column prop="orderId" label="订单编号" ></el-table-column>
            <el-table-column prop="paymentTime" label="下单时间" width="170px"></el-table-column>
            <el-table-column prop="quantity" label="商品数量" ></el-table-column>
            <el-table-column prop="deliveryTime" label="配送时长（min）" width="140px">
                <template slot-scope="scope">
                    {{ scope.row.deliveryTime != null ? scope.row.deliveryTime + '分钟' : '/' }}
                </template>
            </el-table-column>
            <el-table-column prop="status" label="配送状态">
              <template slot-scope="scope">
                <span :style="{ color: 
                    scope.row.status === 0 ? 'black' :
                    scope.row.status === 1 ? 'green' :
                    scope.row.status === 2 ? 'red' :
                    scope.row.status === 3 ? 'grey' :
                    'grey'
                  }">
                  {{
                    scope.row.status === 0 ? '待配送' :
                    scope.row.status === 1 ? '准时配送' :
                    scope.row.status === 2 ? '超时配送' :
                    scope.row.status === 3 ? '取消配送' :
                    '取消配送'
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="courierName" label="配送员" ></el-table-column>
            <el-table-column prop="cityName" label="所在城市" ></el-table-column>
            <el-table-column prop="districtName" label="所在区域"></el-table-column>
            <el-table-column prop="warehouseName" label="仓库名称" ></el-table-column>
        </el-table>

        <el-row>
            <el-col :span="24">
                <!-- 放分页 
                layout：设置页面显示的内容 
                -->
                <el-pagination
                    background
                    :page-sizes="[5,8,10,20,50]"
                    :page-size="pageSize"
                    :current-page="pageNum"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @next-click="nextPage"
                    @prev-click="prevPage"
                    @current-change="pageChange"
                    @size-change="SizeChange">
                </el-pagination>
            </el-col>
        </el-row>

        <router-view></router-view> <!-- 子路由会在这里渲染 -->
    </div>
</template>

<script>
export default {
    data() {
        return {
            deliveryList:[],
            statusOptions: [
              { label: '待配送', value: '0', color: 'black' },
              { label: '准时配送', value: '1', color: 'green' },
              { label: '超时配送', value: '2', color: 'red' },
              { label: '取消配送', value: '3', color: 'grey' }
            ],
            insertChargeDialog: false,
            // 城市选项
            cityOptions: [],
            // 区域选项
            districtOptions: [],
            // 当前选中的城市 ID
            selectedCityId: null,
            param: {
                orderId: '',             // 订单编号
                status: null,            // 配送状态
                cityId: null,            // 城市ID
                districtId: null,        // 区域ID
                minDeliveryTime: '',     // 最小配送时长
                maxDeliveryTime: '',     // 最大配送时长
                minQuantity: '',         // 最小商品数量
                maxQuantity: '',         // 最大商品数量
                paymentTime: []          // 下单时间范围
            },
            pageSize:8,
            pageNum:1,
            total:100
        }
    },
    methods: {
        queryDeliveryByConditionBtn(){
            // 验证配送时长范围
        if (this.param.minDeliveryTime && this.param.maxDeliveryTime) {
            if (Number(this.param.minDeliveryTime) > Number(this.param.maxDeliveryTime)) {
                this.$message.warning('最小配送时长不能大于最大配送时长');
                return;
            }
        }
        
        // 验证商品数量范围
        if (this.param.minQuantity && this.param.maxQuantity) {
            if (Number(this.param.minQuantity) > Number(this.param.maxQuantity)) {
                this.$message.warning('最小商品数量不能大于最大商品数量');
                return;
            }
        }
            this.pageNum = 1;
            this.queryDeliveryByCondition();
        },
        //加载分拣数据
        queryDeliveryByCondition(){
            
            
            const { paymentTime, ...rest } = this.param;
            rest.startTime = paymentTime && paymentTime.length > 0 ? paymentTime[0] : '';
            rest.endTime = paymentTime && paymentTime.length > 0 ? paymentTime[1] : '';
            const pageParam = {
                param: rest,
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                startTime: paymentTime && paymentTime.length > 0 ? paymentTime[0] : '',
                endTime: paymentTime && paymentTime.length > 1 ? paymentTime[1] : ''
            };
            
            
            this.$axios.post('/api/delivery/queryDeliveryByCondition', pageParam)
            .then(resp => {
                if (resp.data.code === 200) {
                    this.deliveryList = resp.data.data.list;
                    this.total = resp.data.data.total;
                } else {
                    this.$message.error(resp.data.msg || '查询失败');
                }
            })
            .catch(error => {
                console.error('查询配送数据失败:', error);
                this.$message.error('查询配送数据失败');
            });
        },
        //加载城市数据
        loadCities(){
            this.$axios.get('api/warehouse/queryCities')
            .then(resp => {
                if(resp.data.code == 200){
                    this.cityOptions = resp.data.data.map(city => ({
                        label: city.name,
                        value: city.id
                    }));
                }
            })
        },
        // 加载区域数据
        loadDistricts(cityId) {
            this.$axios.get('api/warehouse/queryDistricts/'+cityId)
            .then(resp => {
                if(resp.data.code == 200){
                    this.districtOptions = resp.data.data.map(district => ({
                        label: district.name,
                        value: district.id
                    }));
                }
            })
        },
        resetForm() {
            //重置
            this.param = {
                orderId: '',             // 订单编号
                status: null,            // 配送状态
                cityId: null,            // 城市ID
                districtId: null,        // 区域ID
                minDeliveryTime: '',     // 最小配送时长
                maxDeliveryTime: '',     // 最大配送时长
                minQuantity: '',         // 最小商品数量
                maxQuantity: '',         // 最大商品数量
                paymentTime: []          // 下单时间范围
            };
            this.districtOptions = [];
            this.queryDeliveryByCondition();
        },
            nextPage(val){
                //用户点击下一页触发
                //val代表当前页
                this.pageNum = val;
                this.queryDeliveryByCondition();
            },
            prevPage(val){
                //用户点击上一页触发
                //val代表当前页
                this.pageNum = val;
                this.queryDeliveryByCondition();
            },
            pageChange(val){
                //直接切换界面
                this.pageNum = val;
                this.queryDeliveryByCondition();
            },
            SizeChange(val){
                //改变查询"几条/页"
                this.pageSize = val;
                this.queryDeliveryByCondition();
            }
        
    },
    watch: {
        // 监听城市ID变化
        'param.cityId'(newVal) {
            this.param.districtId = null; // 清空已选区域
            if(newVal) {
                this.loadDistricts(newVal);
            } else {
                this.districtOptions = [];
            }
        }
    },
    created() { 
        this.queryDeliveryByCondition();
        this.loadCities();
    },
}
</script>